/*
 * @Author: huyu
 * @Date: 2020-06-06 11:33:11
 * @Last Modified by: huyu
 * @Last Modified time: 2020-06-20 21:47:16
 */

// 博客布局组件

import React, { Component } from "react"
import Header from "./Header"
import Content from "./Content"
import Footer from "./Footer"
import ToTop from "../ToTop"

import style from "./index.module.less"

export default class BlogLayout extends Component {
  constructor(props) {
    super(props)
    this.state = {
      // 是否展示头部阴影
      showHeaderShadow: false,
      // 是否展示回到顶部组件
      showToTop: false,
    }
  }

  componentDidMount() {
    this._init()
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this._onScroll)
  }

  // 初始化操作
  _init = () => {
    window.addEventListener("scroll", this._onScroll)
  }

  // 监听html滚动据里
  _onScroll = e => {
    // 在微信和钉钉内置内打开时，只有使用document.getElementsByTagName("body")[0].scrollTop才能获取到有效的scrollTop值
    let scrollTop = Math.max(
      document.documentElement.scrollTop,
      document.getElementsByTagName("body")[0].scrollTop
    )
    let { showHeaderShadow, showToTop } = this.state
    if (scrollTop > 60 && !showHeaderShadow) {
      this.setState({ showHeaderShadow: true })
    } else if (scrollTop === 0 && showHeaderShadow) {
      this.setState({ showHeaderShadow: false })
    }
    if (scrollTop > window.innerHeight && !showToTop) {
      this.setState({ showToTop: true })
    } else if (scrollTop < window.innerHeight && showToTop) {
      this.setState({ showToTop: false })
    }
  }

  render() {
    const { showHeaderShadow, showToTop } = this.state
    const { title, showFooter = true, showNav, headings } = this.props
    return (
      <div className={style.main}>
        <Header
          title={showHeaderShadow ? title : ""}
          showNav={showNav}
          showHeaderShadow={showHeaderShadow}
        />
        <Content headings={headings}>{this.props.children}</Content>
        {showFooter && <Footer />}
        {showToTop && <ToTop />}
      </div>
    )
  }
}
